package com.atguigu.gmall.payment;

import com.atguigu.gmall.enums.model.PaymentStatus;
import com.atguigu.gmall.enums.model.PaymentType;
import com.atguigu.gmall.enums.model.PaymentWay;
import com.atguigu.gmall.payment.model.PaymentInfo;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import com.atguigu.gmall.rabbit.config.MqConst;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: atguigu
 * @create: 2023-08-15 09:26
 */
@Slf4j
@Component
public class PaymentRecevier {


    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private AlipayService alipayService;

    /***
     * 监听关闭交易消息（订单超时关闭），将本地交易，支付宝交易同样关闭
     * @param outTradeNo 订单编号
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_CLOSE, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_PAYMENT_CLOSE, durable = "true"),
            key = MqConst.ROUTING_PAYMENT_CLOSE
    ))
    public void processCloseTrade(String outTradeNo, Channel channel, Message message) {
        if (StringUtils.isNotBlank(outTradeNo)) {
            log.info("[支付服务]监听到关闭交易消息：{}", outTradeNo);
            //1.查询本地交易记录是否存在，如果存在修改状态为关闭
            PaymentInfo paymentInfo = paymentInfoService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
            if (paymentInfo != null) {
                paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
                paymentInfoService.updateById(paymentInfo);
                //2.查询支付宝交易记录是否存在，如果存在将交易关闭
                //2.1 调用支付宝接口查询支付宝交易 如果状态：等待买家付款
                String alipayStatus = alipayService.getAliPayTradeSatus(paymentInfo);
                //2.2 调用支付宝接口关闭支付宝交易
                if("WAIT_BUYER_PAY".equals(alipayStatus)){
                    alipayService.closeAlipayTrade(paymentInfo);
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
